package com.sl.ffmpeg_plugin

import android.media.MediaMetadataRetriever
import android.util.Log
import io.flutter.plugin.common.MethodChannel
import io.microshow.rxffmpeg.RxFFmpegCommandList
import io.microshow.rxffmpeg.RxFFmpegInvoke
import io.microshow.rxffmpeg.RxFFmpegProgress
import io.microshow.rxffmpeg.RxFFmpegSubscriber
import io.reactivex.disposables.Disposable
import io.reactivex.subscribers.DisposableSubscriber
import java.io.File

class VideoManager() {

    var commendArray: Array<String>? = null

    var sub: DisposableSubscriber<RxFFmpegProgress>? = null

    fun addCommend(commendList: List<String>) {
        var cmdList = RxFFmpegCommandList()
        commendList.forEach {
            cmdList.append(it)
        }
        commendArray = cmdList.build()
    }


    fun setCommend(commend: String) {
        commendArray = commend.split(" ").toTypedArray()
    }

    fun executeCommend(channel: MethodChannel) {
        sub = object : RxFFmpegSubscriber() {
            override fun onFinish() {
                channel.invokeMethod("success", null)
            }

            override fun onCancel() {
                channel.invokeMethod("cancel", null)
            }

            override fun onProgress(progress: Int, progressTime: Long) {
                Log.e("error", progress.toString())
                channel.invokeMethod("progressListener", mapOf("data" to mapOf("progress" to progress, "progressTime" to progressTime)))
            }

            override fun onError(message: String?) {
                channel.invokeMethod("error", mapOf("data" to mapOf("errorMessage" to message)))
            }
        }
        RxFFmpegInvoke.getInstance().runCommandRxJava(commendArray).subscribe(sub!!)
    }

    fun cancel(channel: MethodChannel) {
        RxFFmpegInvoke.getInstance().exit()
        sub?.dispose()
        channel.invokeMethod("cancel", null)
    }


    fun getVideoInfo(videoPath: String): VideoOption {
        val retr = MediaMetadataRetriever()
        var file = File(videoPath) //解决魅族手机崩溃问题
        retr.setDataSource(file.absolutePath)
        val opt = VideoOption()
        opt.run {
            height = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)
            width = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)
            rotation = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION)
        }
        return opt
    }

    class VideoOption {
        var height: String = "";
        var width: String = "";
        var rotation = "";
    }

}